package main;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.util.Calendar;
import java.util.Date;
import java.util.Properties;

/**
 * Created by Administrator on 2017/4/26.
 */

public class MAPI {
    private static long g4SYS_CHECK_USE_TIME;

    public static int RD_PRIVATE_VALUE(int key, String fileName) {
        return RD_PRIVATE_VALUE(String.format("%d", key), fileName);
    }
    public static int RD_PRIVATE_VALUE(String pKey, String fileName) {
        return MAPI.STRING_DEC32(RD_PRIVATE_STRING(pKey, fileName));
    }
    public static String RD_PRIVATE_STRING(int key, String fileName) {
        return RD_PRIVATE_STRING(String.format("%d", key), fileName);
    }
    public static String RD_PRIVATE_STRING(String pKey, String fileName) {
        return READ_PRIVTE_PROFILE("", pKey, fileName);
    }
    public static void WR_PRIVATE_VALUE(int key, int value, String fileName) {
        WR_PRIVATE_VALUE(String.format("%d", key), value, fileName);
    }
    public static void WR_PRIVATE_VALUE(String pKey, int value, String fileName) {
        WR_PRIVATE_STRING(pKey, String.format("%d", value), fileName);
    }
    public static void WR_PRIVATE_STRING(int key, String pValue, String fileName) {
        WR_PRIVATE_STRING(String.format("%d", key), pValue, fileName);
    }
    public static void WR_PRIVATE_STRING(String pKey, String pValue, String fileName) {   // 写入Properties信息
        if (pKey == null || pValue == null || fileName == null){
            return;
        }
        WRITE_PRIVTE_PROFILE(pKey, pValue, fileName);
    }

    public static void MSLEEP(int g4Local_1){
        try {
            Thread.sleep(g4Local_1);
        } catch (InterruptedException e) {
        }

    }
    public static void CHECK_USE_TIME_START(){
        g4SYS_CHECK_USE_TIME = System.currentTimeMillis();
    }
    public static String CHECK_USE_TIME_SHOW(){
        long g4Local_1;
        String gsLocal_1;

        g4Local_1 = System.currentTimeMillis() - g4SYS_CHECK_USE_TIME;
        if (g4Local_1 < 1000){
            gsLocal_1 = String.format("%d毫秒", g4Local_1);
        }
        else {
            gsLocal_1 = String.format("%d.%d秒", g4Local_1/1000, g4Local_1%1000);
        }
        return gsLocal_1;
    }
    public static void COPY_BUFF8(int length, int in_offset, byte[]in_data, int out_offset, byte[]out_data){     // 将一个缓冲复制到另一个缓冲
        int g4Local_1 = 0;
        do {
            out_data[g4Local_1 + out_offset] = in_data[g4Local_1 + in_offset];
        } while (++g4Local_1 < length);
    }
    public static void FILL_BUFF8(int fill, int length, int out_offset, byte[]out_data){     // 将一个缓冲复制到另一个缓冲
        int g4Local_1 = 0;
        do {
            out_data[g4Local_1 + out_offset] = (byte)fill;
        } while (++g4Local_1 < length);
    }
    public static void CLEAR_BUFF8(int length, int out_offset, byte[]out_data){     // 将一个缓冲复制到另一个缓冲
        int g4Local_1 = 0;
        do {
            out_data[g4Local_1 + out_offset] = 0;
        } while (++g4Local_1 < length);
    }
    public static int COMP_BUFF8(int length, int in_offset, byte[]in_data, int out_offset, byte[]out_data){     // 两个缓冲比较相同则返回0
        int g4Local_1 = 0;
        do {
            if (out_data[g4Local_1 + out_offset] != in_data[g4Local_1 + in_offset]){
                return 1;
            }
        } while (++g4Local_1 < length);
        return 0;
    }
    public static int BUFF8_WORD(int in_offset, byte[]in_data){           // 将一个缓冲转换DWORD
        return (short)((in_data[in_offset+1]<<8)&0x0000ff00) | (in_data[in_offset]&0x000000ff);
    }
    public static int BUFF8_3BYTE(int in_offset, byte[] in_data) { // 将一个缓冲转换为3BYTE
        int g4Local_1 = in_data[in_offset + 2] & 0xff;
        g4Local_1 = (g4Local_1 << 8) | (in_data[in_offset + 1] & 0xff);
        g4Local_1 = (g4Local_1 << 8) | (in_data[in_offset] & 0xff);
        return g4Local_1;
    }
    public static int BUFF8_DWORD(int in_offset, byte[]in_data){           // 将一个缓冲转换为DWORD
        int g4Local_1 = ((in_data[in_offset+1]<<8)&0x0000ff00) | (in_data[in_offset]&0x000000ff);
        int g4Local_2 = ((in_data[in_offset+3]<<24)&0xff000000) | ((in_data[in_offset+2]<<16)&0x00ff0000);
        return g4Local_2 | g4Local_1 ;
    }
    public static void WORD_BUFF8(int g4Local_1, int in_offset, byte[]in_data){           // 将WORD转换到缓冲
        in_data[in_offset] = (byte)g4Local_1;
        in_data[in_offset+1] = (byte)(g4Local_1 >> 8);
    }
    public static void M3BYTE_BUFF8(int g4Local_1, int in_offset, byte[] in_data) { // 将DWORD转换到缓冲
        in_data[in_offset] = (byte) g4Local_1;
        in_data[in_offset + 1] = (byte) (g4Local_1 >> 8);
        in_data[in_offset + 2] = (byte) (g4Local_1 >> 16);
        return;
    }
    public static void DWORD_BUFF8(int g4Local_1, int in_offset, byte[]in_data){           // 将DWORD转换到缓冲
        in_data[in_offset] = (byte)g4Local_1;
        in_data[in_offset+1] = (byte)(g4Local_1 >> 8);
        in_data[in_offset+2] = (byte)(g4Local_1 >> 16);
        in_data[in_offset+3] = (byte)(g4Local_1 >> 24);
    }
    //    public static long STRING_DEC64(int offset, String gsLocal_1) {                        // 从字符串返回十进制的数字
//        if ("".equals(gsLocal_1)){
//        	return 0;
//        }
//    	return Integer.valueOf(gsLocal_1);
//    }
    public static int STRING_DEC32(String gsLocal_1) {                        // 从字符串返回十进制的数字
        if (gsLocal_1 == null || "".equals(gsLocal_1)){
            return 0;
        }
        int g4Local_1 = gsLocal_1.length();
        int g4Local_2 = 0;
        int g4Local_3 = 0;
        char g2Local_1;
//MDWORD(0x99);MSTRING(gsLocal_1);
        do {
            g2Local_1 = (char)gsLocal_1.charAt(g4Local_2);
//MDWORD(g2Local_1);
            if (g2Local_1 < '0' || g2Local_1 > '9'){
                break;
            }
            g2Local_1 -= '0';
            g4Local_3 = (g4Local_3 * 10) + g2Local_1;
        } while (++g4Local_2 < g4Local_1);
        return g4Local_3;
    }
    public static int STRING_BUFF8(String gsLocal_1, int maxLength, int offset, byte[]out_data) {         // 将显示串的内容转换为缓冲
        char g2Local_1;
        int g4Local_1 = 0;
        if ("".equals(gsLocal_1)){
            return 0;
        }
        int g4Local_2 = gsLocal_1.length();
        do {
            if (g4Local_1 >= maxLength){
                break;
            }
            g2Local_1 = gsLocal_1.charAt(g4Local_1);
            out_data[offset++] = (byte)g2Local_1;
        } while (++g4Local_1 < g4Local_2);
        return g4Local_1;
    }

    public static String BUFF8_STRING(int maxLength, int in_offset, byte[]in_data){                        // 将一个缓冲的内容转换为显示串
        int g4Local_1 = maxLength/2;
        char[] g2Local_Buffer = new char[g4Local_1];
        int g4Local_2 = 0;
        do {
            g2Local_Buffer[g4Local_2] = (char)(((in_data[in_offset+1]&0xff)<<8) | (in_data[in_offset]&0xff));
            if (g2Local_Buffer[g4Local_2] == 0){
                break;
            }
            in_offset += 2;
        } while (++g4Local_2 < g4Local_1);
        return new String(g2Local_Buffer, 0, g4Local_2);
    }
    public static String ASCII_STRING(int maxlength, int in_offset, byte[]in_data){           // 将一个缓冲的内容转换为显示串
        int g4Local_1 = 0;
        do {
            if (in_data[in_offset+g4Local_1] == 0){
                break;
            }
        } while (++g4Local_1 < maxlength);
        if (maxlength == 0){
            return "";
        }
        char[] gpLocal_2 = new char[g4Local_1];
        int g4Local_2 = 0;
        do {
            gpLocal_2[g4Local_2] = (char)in_data[in_offset+g4Local_2];
        } while (++g4Local_2 < g4Local_1);
        return String.valueOf(gpLocal_2);
    }
    public static String DATE_TIME_STRING(int mode, int dateTime){
        byte[] gpLocal_1 = new byte[4];
        MAPI.DWORD_BUFF8(dateTime, 0, gpLocal_1);
        return MAPI.DATE_TIME_STRING(mode, 0, gpLocal_1);
    }
    public static String DATE_TIME_STRING(int mode, int offset, byte[] in_data){
        int g2Local_1;
        String gsLocal_1 = "";
        String gsLocal_2;

        if ((mode & 0x01) > 0){
            if ((mode & 0x80) > 0){
                g2Local_1 = MAPI.BUFF8_WORD(offset + 2, in_data) & 0xffff;
            }
            else {
                g2Local_1 = MAPI.BUFF8_WORD(mode==1 ? offset : offset+2, in_data) & 0xffff;
            }
            if ((mode & 0x40) == 0){
                gsLocal_2 = String.format("%d-", (g2Local_1 / (12 * 31)) + 2010);	// 不显示年
                gsLocal_1 += gsLocal_2;
            }
            g2Local_1 = g2Local_1 % (12 * 31);
            gsLocal_2 = String.format("%02d", (g2Local_1 / 31)+1);
            gsLocal_1 += gsLocal_2;
            gsLocal_2 = String.format("-%02d ", (g2Local_1 % 31)+1);
            gsLocal_1 += gsLocal_2;
        }
        if ((mode & 0x02) > 0){
            g2Local_1 = MAPI.BUFF8_WORD(offset,  in_data) & 0xffff;				// 时间=24小时*60分*30秒，秒只有双数
            gsLocal_2 = String.format("%02d", g2Local_1 / (60 * 30));
            gsLocal_1 += gsLocal_2;
            g2Local_1 = g2Local_1 % (60 * 30);
            gsLocal_2 = String.format(":%02d", g2Local_1 / 30);
            gsLocal_1 += gsLocal_2;
            gsLocal_2 = String.format(":%02d", (g2Local_1 % 30) * 2);
            gsLocal_1 += gsLocal_2;
        }
        return gsLocal_1;
    }
    public static short ADD_DATE_WORD(int year, int month, int day){
//MAPI.SYS_DEC(year);MAPI.SYS_DEC(month);MAPI.SYS_DEC(day);
        if ((month > 0 && month <= 12) && (day > 0 && day <= 31)){
            return (short)((year*12*31) + ((month-1)*31) + (day-1));
        }
        return 0;
    }
    public static short ADD_TIME_WORD(int hour, int minute, int second){
        if (hour < 24 && minute < 60 && second < 60){
            return (short)((hour*60*30) + (minute*30) + (second/2));
        }
        return 0;
    }
    public static int LONG_FAST_DWORD(long dataTime){
        Calendar calendar = Calendar.getInstance();
        if (dataTime == 0){
            calendar.setTime(new Date());
        }
        else {
            calendar.setTime(new Date(dataTime));
        }
        int g4Local_1 = ADD_DATE_WORD(calendar.get(Calendar.YEAR)-2010, calendar.get(Calendar.MONTH)+1, calendar.get(Calendar.DAY_OF_MONTH));
        int g4Local_2 = ADD_TIME_WORD(calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), calendar.get(Calendar.SECOND));
        return (g4Local_2 & 0xffff) | ((g4Local_1 & 0xffff) << 16);
    }
    public static String IPADDR_STRING(int IPAddr){                        // 将IP地址转换为显示串
        String gsLocal_1 = String.format("%d.%d.%d.%d", IPAddr&0xff,(IPAddr>>8)&0xff,(IPAddr>>16)&0xff,(IPAddr>>24)&0xff);
        return gsLocal_1;
    }
    public static String IPADDR_STRING(int offset, byte[] in_data){       // 将IP地址转换为显示串
        String gsLocal_1 = String.format("%d.%d.%d.%d", in_data[offset]&0xff,in_data[offset+1]&0xff,in_data[offset+2]&0xff,in_data[offset+3]&0xff);
        return gsLocal_1;
    }
    public static int STRING_ASCII_HEX(String gsLocal_1, int length, int offset, byte[] out_data){
        if ("".equals(gsLocal_1)){
            return 0;
        }
        int g4Local_1 = length * 2;
        int g4Local_2 = gsLocal_1.length();
        if (g4Local_2 > g4Local_1){
            g4Local_2 = g4Local_1;
        }
//MAPI.DEBUG(0xad);MAPI.DEBUG(account.length());
        int gLocal_1;
        int gLocal_2 = 0;
        g4Local_1 = 0;
        do {
            gLocal_1 = MAPI.ASCII_HEX(gsLocal_1.charAt(g4Local_1));
            if ((g4Local_1 & 0x01) == 0){
                gLocal_2 = gLocal_1;
            }
            else {
                out_data[offset++] = (byte)(((gLocal_2&0xff) << 4) | (gLocal_1&0xff));
            }
        } while (++g4Local_1 < g4Local_2);
        return g4Local_1;
    }
    public static String HEX_STRING_ASCII(int length, int offset, byte[] in_data){	// 从HEX转换到串
        int g2Local_1 = 0;
        char[] g2Local_Buffer = new char[length * 2];
        int g4Local_1 = 0;
        do {
            g2Local_Buffer[g4Local_1++] = (char)MAPI.HEX_ASCII(in_data[offset+g2Local_1] >> 4);
            g2Local_Buffer[g4Local_1++] = (char)MAPI.HEX_ASCII(in_data[offset+g2Local_1] & 0x0f);
        } while (++g2Local_1 < length);
        return String.valueOf(g2Local_Buffer);
    }
    public static byte HEX_ASCII(int gLocal_1){			  // 从8位的HEX转换到ASCII码
        gLocal_1 &= 0x0f;
        if (gLocal_1 < 0x0a){
            return (byte)(gLocal_1 += '0');
        }
        return (byte)((gLocal_1 - 10) + 'a');
    }
    public static byte ASCII_HEX(int gLocal_1){							// 从ASCII码转换到8位的HEX
        if ((gLocal_1 > ('0'-1)) && (gLocal_1 < ('9'+1))){
            gLocal_1 = gLocal_1 - '0';
        }
        else if ((gLocal_1 > ('A'-1)) && (gLocal_1 < ('F'+1))){
            gLocal_1 = gLocal_1 - 'A' + 10;
        }
        else if ((gLocal_1 > ('a'-1)) && (gLocal_1 < ('f'+1))){
            gLocal_1 = gLocal_1 - 'a' + 10;
        }
        else {
            gLocal_1 = 0xff;
        }
        return (byte)(gLocal_1 & 0xff);
    }
    public static int MAPI_FILE_DWORD_CHECKSUM(int length, int offset, byte[] in_data){								// 计算文件的以32位为单位的CHECKSUM，返回CHECKSUM
        int g4Local_2;
        int g4Local_3;

        g4Local_2 = 0;
        g4Local_3 = 0;
        do {
            g4Local_3 += BUFF8_DWORD(offset+g4Local_2,in_data);
            g4Local_2 += 4;
        } while (g4Local_2 < length);
        return g4Local_3;
    }
    public static byte COUNTING_PERCENT(int current, int total){
        if(total > 100){
            total = total / 100;
        }
        else{
            current *= 100;
            if (total == 0){
                total = 1;
            }
        }
        current = current / total;
        if (current > 100){
            current = 100;
        }
        return (byte)current;
    }

    public static void DELETE_FILE(String fileName){			  // 删除文件
        File gfLocal_1 = new File(fileName);
        if (gfLocal_1.exists()) {
            gfLocal_1.delete();
        }
    }
    public static void COPY_FILE(String sourceFile, String targetFile){			// 复制文件
        FileChannel in = null;
        FileChannel out = null;
        FileInputStream inStream = null;
        FileOutputStream outStream = null;
        try {
            inStream = new FileInputStream(sourceFile);
            outStream = new FileOutputStream(targetFile);
            in = inStream.getChannel();
            out = outStream.getChannel();
            in.transferTo(0, in.size(), out);
        } catch (IOException e) {
        } finally {
            try {
                inStream.close();
                in.close();
                outStream.close();
                out.close();
            } catch (IOException e) {
            }
        }
    }
    public static long GET_FILE_LENGTH(String fileName){
        File file = new File(fileName);
        return file.length();
    }
    public static long GET_FILE_DATE_TIME(String fileName){
        File file = new File(fileName);
        return MAPI.LONG_FAST_DWORD(file.lastModified());
    }
    public static int WRITE_BUFF8_FILE(int add, int length, int offset, byte[]in_data, String fileName){
        if (add == 0){
            DELETE_FILE(fileName);
        }
        try {
            RandomAccessFile gfLocal_1;
            gfLocal_1 = new RandomAccessFile(fileName, "rw");
            if (add > 0){
                gfLocal_1.seek(gfLocal_1.length());
            }
            gfLocal_1.write(in_data, offset, length);
            gfLocal_1.close();
            return length;
        } catch (IOException e) {
        }
        return 0;
    }
    public static String READ_TEXT_FILE(String fileName){
        try {
            RandomAccessFile gfLocal_1;
            gfLocal_1 = new RandomAccessFile(fileName, "rw");
            int length = (int)gfLocal_1.length();
            if (length > 0) {
                byte[] gpLocal_1 = new byte[length];
                gfLocal_1.read(gpLocal_1, 0, length);
                gfLocal_1.close();
//MSYS.MSTRING("READ_TEXT_FILE 1 " + length);
                return new String(gpLocal_1, 0, gpLocal_1.length, "utf-8");
            }
        } catch (IOException e) {
        }
        return "";
    }
    public static String READ_AND_REMOVE_TEXT_LINE(String fileName){
        String gsLocal_1 = "";
        try {
            RandomAccessFile gfLocal_1;
            gfLocal_1 = new RandomAccessFile(fileName, "rw");
            int g4Local_1 = (int)gfLocal_1.length();
            byte[] gpLocal_1 = new byte[g4Local_1];
            gfLocal_1.read(gpLocal_1, 0, g4Local_1);
            gfLocal_1.close();
            int g4Local_2 = 0;
            while (g4Local_2 < g4Local_1){
                if (gpLocal_1[g4Local_2] == '\r'){
                    break;
                }
                ++g4Local_2;
            }
            gsLocal_1 = new String(gpLocal_1, 0, g4Local_2);
            while (g4Local_2 < g4Local_1){
                if (gpLocal_1[g4Local_2] >= ' '){
                    break;
                }
                ++g4Local_2;
            }
            WRITE_BUFF8_FILE(0, g4Local_1-g4Local_2, g4Local_2, gpLocal_1, fileName);
        } catch (IOException e) {
        }
        return gsLocal_1;
    }

    public static void WRITE_PRIVTE_PROFILE(String pKey, String pValue, String filePath) {   // 写入Properties信息
//        MDEBUG(0xa1);MSTRING(filePath);
        Properties pps = new Properties();
        File file = new File(filePath);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
            }
        }
        InputStream in = null;
        try {
            in = new FileInputStream(filePath);
        } catch (FileNotFoundException e) {
            return;
        }
        try {
            pps.load(in);                           //从输入流中读取属性列表（键和元素对）
        } catch (IOException e) {
        }
        OutputStream out = null;                //调用 Hashtable 的方法 put。使用 getProperty 方法提供并行性。
        try {
            out = new FileOutputStream(filePath);
        } catch (FileNotFoundException e) {
        }
        pps.setProperty(pKey, pValue);   //强制要求为属性的键和值使用字符串。返回值是 Hashtable 调用 put 的结果。
        try {
            pps.store(out, "Update " + pKey + " name");     //以适合使用 load 方法加载到 Properties 表中的格式，
        } catch (IOException e) {                           //将此 Properties 表中的属性列表（键和元素对）写入输出流
        }
    }
    public static int READ_PRIVTE_PROFILE_DEC(String key, String filePath) {   // 根据Key读取Value
        return MAPI.STRING_DEC32(READ_PRIVTE_PROFILE("Info", key, filePath));
    }
    public static String READ_PRIVTE_PROFILE(String index, String key, String filePath) {   // 根据Key读取Value
        Properties pps = new Properties();
//MSTRING(filePath);
        try {
            InputStream in = new BufferedInputStream(new FileInputStream(filePath));
            pps.load(in);
            String value = pps.getProperty(key, "");
            return value;

        }catch (IOException e) {
        }
        return "";
    }

    public static String GET_JSON_STRING(String inString, String key) {
        if (inString != null && inString.length() > 5) {
            try {
                JSONObject object = new JSONObject(inString);
                return object.getString(key);
            } catch (JSONException e) {
            }
        }
        return "";
    }
    public static int GET_JSON_DEC32(String inString, String key) {
        if (inString != null && inString.length() > 5) {
            try {
                JSONObject object = new JSONObject(inString);
                return object.getInt(key);
            } catch (JSONException e) {
            }
        }
        return 0;
    }
    public static int SET_KBA_STRING_BUFF8(String gsLocal_1, int maxLength, int offset, byte[] out_data){
        int g4Local_1 = gsLocal_1.length();
        if (maxLength > g4Local_1){
            maxLength = g4Local_1;
        }
        out_data[offset] = (byte)(maxLength & 0xff);
        int g4Local_2 = (1 + (g4Local_1 * 2));
        if (g4Local_1 > 0){
            g4Local_1 = 0;
            do{
                out_data[++offset] = (byte)gsLocal_1.charAt(g4Local_1);
                out_data[++offset] = (byte)(gsLocal_1.charAt(g4Local_1) >> 8);
            } while (++g4Local_1 < maxLength);
        }
        return g4Local_2;
    }
    public static int SET_KBA_ASCII_BUFF8(String gsLocal_1, int maxLength, int offset, byte[] out_data){
        int g4Local_1 = (int)gsLocal_1.length();
        if (gsLocal_1.length() > 0) {
            if (maxLength > g4Local_1) {
                maxLength = g4Local_1;
            }
            int g4Local_2 = maxLength;
            if ((maxLength & 0x01) > 0) {				// 如果是单数的
                g4Local_2 += 1;							// 多占用一个字节
            }
            out_data[offset] = (byte)((g4Local_2/2) & 0xff);
            if (g4Local_1 > 0) {
                g4Local_1 = 0;
                do {
                    out_data[++offset] = (byte)gsLocal_1.charAt(g4Local_1);
                } while (++g4Local_1 < maxLength);
                if ((maxLength & 0x01) > 0) {				// 如果是单数的
                    out_data[++offset] = 0;
                }
            }
            return 1 + g4Local_2;
        }
        out_data[offset] = 0;
        return 1;
    }


}
